package com.neusoft.bizcore.auth.fixture;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import com.neusoft.bizcore.auth.model.AuthOganization;
import com.neusoft.bizcore.auth.model.AuthRole;
import com.neusoft.bizcore.auth.model.AuthUser;
import com.neusoft.bizcore.auth.repository.AuthOganizationRepository;
import com.neusoft.bizcore.auth.repository.AuthRoleRepository;
import com.neusoft.bizcore.auth.repository.AuthUserRepository;
import com.neusoft.bizcore.auth.stress.AuthFixtureEvent;

@Component
public class InitialDataFixture implements CommandLineRunner {

    @Autowired
    private AuthOganizationRepository authOganizationRepository;
    @Autowired
    private AuthUserRepository authUserRepository;
    @Autowired
    private AuthRoleRepository authRoleRepository;
    @Autowired
    ApplicationContext applicationContext;

    @Override
    public void run(final String... args) throws Exception {
        this.init();
        this.applicationContext.publishEvent(new AuthFixtureEvent(this));
    }

    private void init() {

        AuthOganization rootOrg = this.authOganizationRepository.findByCode("root");
        if (null == rootOrg) {
            rootOrg = new AuthOganization();
            rootOrg.setCode("root");
            rootOrg.setName("根组织");
            this.authOganizationRepository.save(rootOrg);
        }

        AuthRole adminRole = this.authRoleRepository.findByCode("admin");
        if (null == adminRole) {
            adminRole = new AuthRole();
            adminRole.setCode("admin");
            adminRole.setName("管理员");
            this.authRoleRepository.save(adminRole);
        }

        AuthUser admin = this.authUserRepository.findByUsername("admin");
        if (null == admin) {
            admin = new AuthUser();
            admin.setUsername("admin");
            admin.setName("管理员");
            admin.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
            admin.setEnabled(true);
            admin.getOganizations().add(rootOrg);
            admin.getRoles().add(adminRole);
            this.authUserRepository.save(admin);
        }

        AuthUser anonymous = this.authUserRepository.findByUsername("anonymous");
        if (null == anonymous) {
            anonymous = new AuthUser();
            anonymous.setUsername("anonymous");
            anonymous.setName("匿名用户");
            anonymous.setPassword(DigestUtils.md5DigestAsHex("anonymous".getBytes()));
            anonymous.setEnabled(true);
            anonymous.getOganizations().add(rootOrg);
            anonymous.getRoles().add(adminRole);
            this.authUserRepository.save(anonymous);
        }
    }

}
